import 'dart:convert';
import 'dart:ffi';

import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_web_page/common_web_page.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/generated/l10n.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_register/company_register_page.dart';
import 'package:e_reception_flutter/ui/login/login_auth/login_auth_page.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/ui/login/login_index/login_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_const.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_sp_lib.dart';

import 'widgets/login_index_edit_phone_widget.dart';
import 'widgets/login_index_go_button_widget.dart';

/// 登录页
///
/// @author: zengxiangxi
/// @createTime: 1/4/21 2:33 PM
/// @specialDemand:
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();

  ///跳转方法
  static Future<bool> navigatorPush(
      BuildContext context) {
    // if(StringUtils.isEmpty(groupId)){
    //   VgToastUtils.toast(context, "分组获取异常");
    //   return null;
    // }
    return RouterUtils.routeForFutureResult<bool>(
      context,
      LoginPage(),
    );
  }
}

class _LoginPageState extends BaseState<LoginPage> {
  LoginViewModel _viewModel;

  ValueNotifier<String> _phoneValueNotifier;

  TapGestureRecognizer _userGestureRecognizer;

  TapGestureRecognizer _privacyGestureRecognizer;

  bool selectionBox = false;

  @override
  void initState() {
    super.initState();
    _viewModel = LoginViewModel(this);
    _phoneValueNotifier = ValueNotifier("");
    _userGestureRecognizer = TapGestureRecognizer()
      ..onTap = () {
        CommonWebPage.navigatorPush(
          context,
          USER_H5,
          "服务协议",
        );
      };
    _privacyGestureRecognizer = TapGestureRecognizer()
      ..onTap = () {
        CommonWebPage.navigatorPush(
          context,
          PRIVACY_H5,
          "隐私政策",
        );
      };

    SharePreferenceUtil.getString(SP_CHOICE_AGREEMENT).then((value){
      if(value!=null){
        selectionBox = true;
      }
      setState(() { });
    });
  }

  @override
  void dispose() {
    _phoneValueNotifier?.dispose();
    _userGestureRecognizer?.dispose();
    _privacyGestureRecognizer?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _toScaffoldWidget();
  }

  Widget _toScaffoldWidget() {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(child: _toMainColumnWidget()),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        SizedBox(
            height: ScreenUtils.getStatusBarH(context),
            width: ScreenUtils.screenW(context)),
        _toCloseButtonWidget(),
        SizedBox(height: 30),
        _toTitleWidget(),
        SizedBox(height: 40),
        _toEditPhoneWidget(),
        SizedBox(height: 30),
        _toGetAuthButtonWidget(),
        SizedBox(height: 15),
        // _toRegisterCompanyWidget(),
        Spacer(),
        _toAgreementWidget(),
        SizedBox(height: ScreenUtils.getBottomBarH(context) + 60)
      ],
    );
  }

  ///关闭按钮
  Widget _toCloseButtonWidget() {
    return Align(
      alignment: Alignment.centerLeft,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          RouterUtils.popOrExit(context);
        },
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 31.7, vertical: 13.7),
          child: Image.asset(
            "images/login_close_ico.png",
            width: 16.6,
            gaplessPlayback: true,
          ),
        ),
      ),
    );
  }

  ///标题
  Widget _toTitleWidget() {
    return Text(
      S.of(context)?.login_index_title ?? "",
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        fontSize: 24,
      ),
    );
  }

  ///输入手机号
  Widget _toEditPhoneWidget() {
    return LoginIndexEditPhoneWidget(
      phoneValueNotifier: _phoneValueNotifier,
    );
  }

  ///获取验证码
  Widget _toGetAuthButtonWidget() {
    return LoginIndexGoButtonWidget(
      _phoneValueNotifier,selectionBox: selectionBox,
      onPhoneTap: (String phone) {
        if (ConstantRepository.of().isJumpLoginAuthCode()) {
          VgToastUtils.toast(context, "测试服跳过获取验证码~");
          LoginAuthPage.navigatorPush(context, phone);
          VgHudUtils.hide(context);
          // _viewModel?.searchOrganization(context, phone,BaseCallback(onSuccess: (val) {
          //   LoginSearchOrganizationBean bean = LoginSearchOrganizationBean.fromMap(val);
          //     LoginAuthPage.navigatorPush(context, phone,bean);
          //   VgHudUtils.hide(context);
          // }, onError: (msg) {
          //   VgHudUtils.hide(context);
          //   VgToastUtils.toast(context, msg);
          // }));
          return;
        }
        _viewModel.sendSmsCode(context, phone, () {
          LoginAuthPage.navigatorPush(context, phone);
        });
        // _viewModel.sendSmsCode(context, phone, () {
        //   _viewModel?.searchOrganization(context, phone,BaseCallback(onSuccess: (val) {
        //     LoginSearchOrganizationBean bean = LoginSearchOrganizationBean.fromMap(val);
        //     LoginAuthPage.navigatorPush(context, phone);
        //     VgHudUtils.hide(context);
        //   }, onError: (msg) {
        //     VgHudUtils.hide(context);
        //     VgToastUtils.toast(context, msg);
        //   }));
        // });
      },
    );
  }

  ///注册账号
  // Widget _toRegisterCompanyWidget() {
  //   return GestureDetector(
  //     behavior: HitTestBehavior.translucent,
  //     onTap: () {
  //       CompanyRegisterPage.navigatorPush(context);
  //     },
  //     child: Container(
  //       padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
  //       child: Row(
  //         mainAxisSize: MainAxisSize.min,
  //         children: <Widget>[
  //           Image.asset("images/login_add_company_ico.png",
  //               width: 18, gaplessPlayback: true),
  //           SizedBox(width: 6),
  //           Text(
  //             "注册账号",
  //             maxLines: 1,
  //             overflow: TextOverflow.ellipsis,
  //             style: TextStyle(
  //               color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
  //               fontSize: 17,
  //             ),
  //           )
  //         ],
  //       ),
  //     ),
  //   );
  // }

  ///隐私协议说明
  Widget _toAgreementWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      // onTap: () {
      //   CommonWebPage.navigatorPush(
      //     context,
      //    ServerApi.BASE_URL + "apph5/privacyPolicyBoard.html",
      //     "隐私政策和用户协议",
      //   );
      // },
      child: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 15),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            GestureDetector(
                behavior: HitTestBehavior.translucent,
              onTap: (){
                selectionBox = !selectionBox;
                if(selectionBox){
                  SharePreferenceUtil.putString(SP_CHOICE_AGREEMENT,SP_CHOICE_AGREEMENT);
                }else{
                  SharePreferenceUtil.putString(SP_CHOICE_AGREEMENT,null);
                }
                setState(() { });
              },
                child: Container(
                  padding: const EdgeInsets.only(left: 10,top: 5,bottom: 5,right: 6),
                  child: Image.asset(selectionBox ?"images/login_checkbox1.png" :"images/login_checkbox0.png",
              height: 14,
            ),
                )),
            // SizedBox(width: 6,),
            Text.rich(
              TextSpan(children: [
                TextSpan(
                    text: "登录即同意AI前台",
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        selectionBox = !selectionBox;
                        if(selectionBox){
                          SharePreferenceUtil.putString(SP_CHOICE_AGREEMENT,SP_CHOICE_AGREEMENT);
                        }else{
                          SharePreferenceUtil.putString(SP_CHOICE_AGREEMENT,null);
                        }
                        setState(() { });
                      }
                      ),
                TextSpan(
                    text: " 服务协议 ",
                    recognizer: _userGestureRecognizer,
                    style: TextStyle(
                      color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    )),
                TextSpan(
                    text: "与"
                    // recognizer: TapGestureRecognizer()
                    //   ..onTap = () {
                    //     return;
                    //   }
                      ),
                TextSpan(
                    text: " 隐私政策",
                    recognizer: _privacyGestureRecognizer,
                    style: TextStyle(
                      color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    ))
              ]),
              style: TextStyle(
                  fontSize: 12,
                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),height: 1.4),
              softWrap: true,
            ),
          ],
        ),
      ),
    );
  }
}
